package WebWeiXinLogin

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

var appid = `wx2cdc5da9f0942bd0`
var secret=`40eaef88f7bc0bf4e52c832a8d439cf1`
var redirect_uri = `http%3a%2f%2fvocaloid.utools.club%2fWeiXinCode`
var response_type = `code`
var scope = `snsapi_userinfo`
var state = `123`
var Access_token string
var openid string

type weiDenCode struct {
	Access_token  string
	Expires_in    int
	Refresh_token string
	Openid        string
	Scope         string
}

func WeiXinCode(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
	w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型,加入此选项可以获取前端json类型的上传。
	//第一步：用户同意授权，获取code
	fmt.Println(`第一步：用户同意授权，获取code`)
	fmt.Println("有人来到了这里")
	data := r.URL.Query()
	fmt.Println(data.Get("code"))
	fmt.Println(data.Get("state"))
	code := data.Get("code")
	//第二步：通过code换取网页授权access_token
	//get方法
	fmt.Println(`第二步：通过code换取网页授权access_token`)
	resp, err := http.Get(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=` + appid + `&secret=`+secret+`&code=` + code + `&grant_type=authorization_code`)
	if err != nil {
		fmt.Println("get failed, err:", err)
		return
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("read from resp.Body failed,err:", err)
		return
	}
	fmt.Print(string(body))
	weiDenCodeModel := &weiDenCode{}
	err = json.Unmarshal(body, weiDenCodeModel)
	if err != nil {
		fmt.Println("json unmarshal failed!")
		return
	}
	fmt.Println("转化完成！")
	fmt.Println("Access_token:", weiDenCodeModel.Access_token)
	//第三步：刷新access_token（如果需要）
	fmt.Println(`第三步：刷新access_token（如果需要）`)
	resp, err = http.Get(`https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=` + appid + `&grant_type=refresh_token&refresh_token=` + weiDenCodeModel.Refresh_token)
	if err != nil {
		fmt.Println("get failed, err:", err)
		return
	}
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("read from resp.Body failed,err:", err)
		return
	}
	fmt.Print(string(body))
	weiDenCodeModel2 := &weiDenCode{}
	err = json.Unmarshal(body, weiDenCodeModel2)
	if err != nil {
		fmt.Println("json unmarshal failed!")
		fmt.Println(err)
		return
	}
	if weiDenCodeModel.Access_token == weiDenCodeModel2.Access_token {
		fmt.Println("用户两次一样没有超时")
		Access_token = weiDenCodeModel.Access_token
		openid = weiDenCodeModel.Openid
	} else {
		fmt.Println("用户两次超时了，使用最新的！")
		Access_token = weiDenCodeModel2.Access_token
		openid = weiDenCodeModel2.Openid
	}
	fmt.Println("第三步结束end")

	jsonk := `{"msg":"ok","openid":` +"\""+openid +"\""+ `}`
	fmt.Println("返回前台数据为：", jsonk)
	w.Write([]byte(jsonk)) //给客户端返回数据。
}
